import React, { useState, useCallback, useMemo, useRef } from 'react';
import Taro, { useDidShow } from '@tarojs/taro';
import { View, Text, Image, Input, PickerView, PickerViewColumn } from '@tarojs/components';
import { observer } from 'mobx-react';
import i18n from 'i18n-js';
import regular from '@/utils/regular';
import { DynamicColors, GStyleSheet } from '@/utils/DarkMode';
import PageContainer from '@/components/PageContainer';
import FlexScrollView from '@/components/FlexScrollView';
import ListItem from '@/components/ListItem';
// import Switch from '@/components/BaseSwitch';

import Alert from '@/components/Alert';
import AlarmPushModel, {
  INoitEditParam,
  ISettingEditParam,
  IWxNotDisturbTime,
  getDisturbTimeText,
} from '@/models/alarmPush';
import { useAlarmPushStore } from '@/hooks';
import { formattingNum } from '@/utils';
import phoneIcon from '@/assets/images/icon_phone.png';

import Toast from '@/utils/Toast';
import { GButton } from '@/components/GButton';
import { getPhoneNotiConfig, getSMSNotiConfig } from '@/config/template';
import Switch from '@/components/Switch';
import alarmIcon from '@/assets/images/alarm.png';
import { Backdrop, ConfigProvider } from '@taroify/core';

const supportPhone = getPhoneNotiConfig();
const supportSMS = getSMSNotiConfig();
const supportAddPhone = supportPhone || supportSMS;

const hourOptions: number[] = [];
for (let i = 0; i < 24; i++) {
  hourOptions.push(i);
}

const dstyle = GStyleSheet.create({
  scroll: {
    paddingLeft: 10,
    paddingRight: 10,
  },
  item: {
    borderRadius: 10,
    marginBottom: 20,
    overflow: 'hidden',
    backgroundColor: DynamicColors.cardBackgroundColor,
  },
  button: {
    width: 80,
    height: 30,
    padding: 5,
  },
  title: {
    color: DynamicColors.titleTextColor,
  },
  tip: {
    color: DynamicColors.subTitleTextColor,
    fontSize: 12,
  },
  phoneViewText: {
    fontSize: 18,
    paddingRight: 10,
  },
  phoneViewItem: {
    display: 'flex',
    flex: 1,
    justifyItems: 'center',
    alignItems: 'center',
  },
  switch: {},
  phoneView: {
    padding: 20,
    display: 'flex',
    flexDirection: 'row',
    borderBottomColor: DynamicColors.borderBottomColor,
    borderBottomWidth: 1,
    borderBottomStyle: 'solid',
  },
  bigTtitle: {
    color: DynamicColors.titleTextColor,
    fontSize: 20,
    fontWeight: 500,
  },
  phoneItem: {
    borderRadius: 10,
    padding: 10,
    marginBottom: 10,
  },
  icon: {
    width: 18,
    height: 20,
    marginRight: 6,
  },
  input: {
    flex: 1,
    padding: '10PX 20PX',
    border: '1PX solid #D1D1D1',
    borderRadius: '10PX',
  },
  name: {
    color: DynamicColors.titleTextColor,
    fontWeight: 500,
  },
  flexStart: {
    justifyContent: 'flex-start',
  },
  titleView: {
    justifyContent: 'space-between',
  },
  saveText: {
    color: DynamicColors.tintColor,
    fontSize: 14,
  },
  deleteText: {
    color: DynamicColors.deleteButton,
    fontSize: 14,
  },
  addTipText: {
    color: DynamicColors.normalTextColor,
    fontSize: 14,
    textAlign: 'left',
  },
  titleTips: {
    fontSize: 14,
    color: '#999999',
    display: 'block',
    padding: '0PX 10PX 0PX 12PX',
    height: '100%',
    lineHeight: '100%',
  },
  titleTipsView: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    marginBottom: '10PX',
  },
  alarmIconView: {
    display: 'flex',
    height: '100%',
    position: 'relative',
  },
  backdrop: {
    backgroundColor: 'rgba(0, 0, 0, 0.7)',
    padding: '10PX',
    position: 'absolute',
    borderRadius: 8,
    zIndex: 999,
    width: 220,
  },
  titleTipsImg: {
    height: 20,
    width: 20,
  },
  backdropTriangle: {
    width: '0PX',
    height: '0PX',
    position: 'absolute',
    borderBottom: '8PX solid rgba(0, 0, 0, 0.7)',
    borderRight: '8PX solid transparent',
    borderLeft: '8PX solid transparent',
    top: -8,
    left: 35,
  },
  addInput: {
    borderRadius: 10,
    padding: 5,
    borderColor: DynamicColors.borderBottomColor,
    borderWidth: 1,
    borderStyle: 'solid',
    flex: 1,
    marginLeft: 10,
  },
});

const defaultAreaCode = '+86';

function checkPhone(mobile: string) {
  return mobile && regular.phone.test(mobile) && mobile.length == 11;
}

interface IContact extends Partial<IPeople> {
  index?: number;
  value?: string;
}

const AlarmPush: React.FC = () => {
  const [delShow, setDelShow] = useState(false);
  const delContactRef = useRef<IContact | undefined>(undefined);
  const { phoneMessageSwitch, phoneSwitch, concatList, wechatNotice, wxDoNotDisturb, wxDoNotDisturbTime } =
    useAlarmPushStore();

  const [editTime, setEditTime] = useState<IWxNotDisturbTime | undefined>(undefined);
  const editNotiSwitchRef = useRef<INoitEditParam | undefined>(undefined);
  const [backdropOpen, setBackdropOpen] = useState(false);

  // 记录当前电话号码编辑情况
  const [editList, setEditList] = useState<IContact[]>([{}, {}, {}]);

  const queryData = useCallback(async () => {
    await AlarmPushModel.getContacts();
    await AlarmPushModel.getAlarmSetting();
  }, []);

  useDidShow(() => {
    queryData();
  });

  const goToAddAlarmPhone = useCallback(() => {
    Taro.navigateTo({ url: '/pages/alarmPush/alarmAddressBook' });
  }, []);

  const showDelAlert = useCallback((p: IContact) => {
    setDelShow(true);
    delContactRef.current = p;
  }, []);

  const hideDelAlert = useCallback(() => {
    setDelShow(false);
  }, []);

  const onDelClick = useCallback(async () => {
    hideDelAlert();
    if (delContactRef.current && delContactRef.current.id) {
      Toast.loading('');
      const res = await AlarmPushModel.delete(delContactRef.current.id);
      if (res.success) {
        await AlarmPushModel.getContacts();
        Toast.hideLoading();
      } else {
        Toast.hideLoading();
        Toast.error(res.message || i18n.t('DELETE_FAILED'));
      }
    }
  }, [hideDelAlert]);

  const styles = dstyle.useDynamicStyle();

  const list = useMemo(() => {
    const arr = editList.map(c => (c.index !== undefined ? c : {}));
    for (let index = 0; index < concatList.length; index++) {
      const contact = concatList[index];
      if (index < arr.length) {
        const editItem = arr[index];
        // 没有index的话，表示不在编辑状态，就拿服务器数据填充
        if (editItem.index == undefined) {
          arr[index] = { ...contact };
        }
      }
    }
    return arr;
  }, [concatList, editList]);

  const onChangePhone = useCallback(
    (p: IContact) => {
      if (p.index !== undefined) {
        const arr = [...editList];
        arr[p.index] = p;
        setEditList(arr);
      }
    },
    [editList]
  );

  const onSave = useCallback(
    async (p: IContact) => {
      const { value, mobile, id, index } = p;
      const isEdit = !id || index !== undefined;
      const m = isEdit ? value : mobile;
      if (checkPhone(m)) {
        Toast.loading('');
        const res = await AlarmPushModel.editOrAddContact({ id, mobile: m!, areaCode: defaultAreaCode, name: '' });
        if (res.success) {
          const arr = [...editList];
          const index = p.index;
          if (index !== undefined) {
            // 去除这一项的编辑状态
            const noEditP = { ...p };
            delete noEditP.index;
            arr[index] = noEditP;
            setEditList(arr);
          }
          await AlarmPushModel.getContacts();
          Toast.hideLoading();
        } else {
          Toast.hideLoading();
          Toast.error(res.message || i18n.t('SAVE_FAIL'));
        }
      } else {
        Toast.info(i18n.t('PLEASE_INPUT_RIGHT_ALARM_PHONE'));
      }
    },
    [editList]
  );

  const editCurrentPhoneSwitch = useCallback(async () => {
    if (editNotiSwitchRef.current) {
      // 编辑开关到服务器
      console.log('编辑开关', editNotiSwitchRef.current);
      const res = await AlarmPushModel.editNotiSwitch(editNotiSwitchRef.current);
      queryData();
    }
  }, [queryData]);

  console.log('list', list);

  const switchChange = useCallback(
    (p: INoitEditParam) => {
      editNotiSwitchRef.current = p;
      editCurrentPhoneSwitch();
    },
    [editCurrentPhoneSwitch]
  );

  const wechatChange = useCallback(
    async (p: ISettingEditParam) => {
      // 编辑打开微信通知
      const res = await AlarmPushModel.editWechatSetting(p);
      queryData();
    },
    [queryData]
  );

  const goToNoDisturbance = () => {
    Taro.navigateTo({ url: '/pages/alarmPush/noDisturbanceSetting' });
  };

  return (
    <PageContainer title={i18n.t('ALARM_PUSH')}>
      <View style={{ height: '100%', display: 'flex', flexDirection: 'column' }}>
        <FlexScrollView id='alarmList' scrollStyle={styles.scroll}>
          <View style={styles.item}>
            <ListItem
              extra={
                <Switch
                  style={styles.switch}
                  checked={wechatNotice}
                  onChange={e => {
                    wechatChange({ wechatNotice: e });
                  }}
                />
              }>
              {i18n.t('WECHAT_NOTI')}
            </ListItem>
            {wechatNotice && (
              <View>
                <ListItem
                  onPress={() => {
                    Taro.navigateTo({ url: '/pages/alarmPush/deviceNoti' });
                  }}
                  arrow>
                  {i18n.t('设备订阅管理')}
                </ListItem>
                {/* <ListItem
                  noBorderBottom
                  disabled={!wechatNotice}
                  extra={<Switch style={styles.switch}  disabled={!wechatNotice} checked={wxDoNotDisturb} onChange={(e) => { wechatChange({ wxDoNotDisturb: e.detail.value }) }} />}
                >
                  {i18n.t('DO_NOT_DIATURB_SWITCH')}
                </ListItem> */}
                <ListItem
                  noBorderBottom
                  arrow
                  // onPress={!wechatNotice ? undefined : showTimeEdit}
                  onPress={goToNoDisturbance}
                  extra={<Text>{getDisturbTimeText(wxDoNotDisturbTime)}</Text>}>
                  {i18n.t('免打扰设置')}
                </ListItem>
              </View>
            )}
          </View>

          {supportAddPhone && (
            <View style={styles.titleTipsView}>
              <Text style={styles.titleTips}>{i18n.t('紧急事件通知')}</Text>
              <View style={styles.alarmIconView}>
                <Image
                  src={alarmIcon}
                  style={styles.titleTipsImg}
                  onClick={() => {
                    setBackdropOpen(true);
                  }}
                />
                {backdropOpen && (
                  <View style={{ ...styles.backdrop, top: 30, left: -30 }}>
                    <Text style={{ color: '#fff' }}>{i18n.t('ALARM_TIPS')}</Text>
                    <View style={styles.backdropTriangle} />
                  </View>
                )}
              </View>
              <ConfigProvider
                theme={{
                  backdropBackgroundColor: 'rgba(0,0,0,0)',
                }}>
                <Backdrop
                  open={backdropOpen}
                  closeable
                  onClose={() => {
                    setBackdropOpen(false);
                  }}
                />
              </ConfigProvider>
            </View>
          )}

          {supportAddPhone && (
            <View style={styles.item}>
              <View style={styles.phoneView}>
                <View style={styles.phoneViewItem}>
                  <Text style={styles.phoneViewText}>{i18n.t('短信通知')}</Text>
                  <Switch
                    style={styles.switch}
                    checked={phoneMessageSwitch}
                    onChange={e => {
                      switchChange({ phoneMessageSwitch: e });
                    }}
                  />
                </View>
                <View style={styles.phoneViewItem}>
                  <Text style={styles.phoneViewText}>{i18n.t('电话通知')}</Text>
                  <Switch
                    style={styles.switch}
                    checked={phoneSwitch}
                    onChange={e => {
                      switchChange({ phoneSwitch: e });
                    }}
                  />
                </View>
              </View>
              <View style={{ padding: 10 }}>
                <Text
                  style={{
                    fontSize: 16,
                    padding: '10PX 10PX',
                    display: 'block',
                  }}>
                  {i18n.t('设置联系人')}
                </Text>
                {list.map((i, idx) => {
                  const { id, index, value, mobile } = i;
                  const isEdit = !id || index !== undefined;
                  const phone = isEdit ? value : mobile || '';
                  return (
                    <View style={styles.phoneItem} key={idx}>
                      <View className='centerFlex' style={styles.titleView}>
                        <View className='centerFlex' style={styles.flexStart}>
                          <Image src={phoneIcon} style={styles.icon} />
                          <Text>{`${i18n.t('URGENCY_PHONE')}${idx + 1}`}</Text>
                        </View>
                        {isEdit ? (
                          <Text
                            style={styles.saveText}
                            onClick={() => {
                              onSave(i);
                            }}>
                            {i18n.t('SAVE')}
                          </Text>
                        ) : (
                          <Text
                            style={styles.deleteText}
                            onClick={() => {
                              showDelAlert(i);
                            }}>
                            {i18n.t('DELETE')}
                          </Text>
                        )}
                      </View>
                      <View className='centerFlex' style={{ marginTop: 10 }}>
                        <Input
                          style={styles.input}
                          placeholder={i18n.t('PLEASE_URGENCY_PHONE')}
                          value={phone}
                          onInput={e => {
                            onChangePhone({ ...i, value: e.detail.value, index: idx });
                          }}
                        />
                      </View>
                    </View>
                  );
                })}
              </View>
              <ListItem
                noBorderBottom
                style={{ ...styles.item, padding: '10PX 26PX' }}
                extra={<GButton style={styles.button} text={i18n.t('ADD')} onPress={goToAddAlarmPhone} />}>
                <View>
                  <View>
                    <Text style={styles.title}>{i18n.t('ADD_ALARM_PHONE_TO_ADDRESS_BOOK')}</Text>
                  </View>
                  <View>
                    <Text style={styles.tip}>{i18n.t('ADD_ALARM_PHONE_TIP')}</Text>
                  </View>
                </View>
              </ListItem>
            </View>
          )}
        </FlexScrollView>
      </View>
      <Alert title={i18n.t('SURE_TO_DELETE')} visible={delShow} onCancel={hideDelAlert} onConfirm={onDelClick} />
    </PageContainer>
  );
};

export default observer(AlarmPush);
